<?php

namespace Yj\Crontab;

use App\Dao\Crontab\CrontabDao;
use Hyperf\Crontab\Parser;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Collection;

class CrontabManager
{

    /**
     * @Inject()
     * @var Parser
     */
    protected $parser;

    public function getCrontabList(): array
    {
        $data = $this->getData();
        if($data->isEmpty()){
            return [];
        }
        $last = time();
        $list = [];

        $data->transform(function($item)use($last,&$list) {
            $crontab = new Crontab();
            $crontab->setCrontabId($item->id);
            $crontab->setCallback($item->target);
            $crontab->setType($item->type);
            $crontab->setEnable(true);
            $crontab->setName($item->name);
            $crontab->setRule($item->rule);
            $time = $this->parser->parse($crontab->getRule(),$last);
            if($time){
                    foreach($time as $t){
                        $list[] = clone $crontab->setExecuteTime($t);
                    }
            }
        });

        return $list;
    }


    /**
     * @Inject()
     * @var CrontabDao
     */
    protected $crontabDao;
    public function getData():Collection
    {
       return $this->crontabDao->get();
    }
}